<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 新房接口
 */
class Newhouse extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 列表
     */
    public function list()
    {
        $limit      = input('limit', 10);
        $page       = input('page', 1);
        $region     = input('region');
        $price      = input('price');
        $category   = input('category');
        $structure  = input('structure');
        $area       = input('area');
        $keyword    = input('keyword', '');

        $newhouse   = model('newhouse');
        $with[] = 'structureList';
        if ($category > -1 || $structure > -1 || $price > -1 || $area > -1) {
            $order = 'newhouse.weigh desc';
            $group = 'newhouse.id';
            if ($region > -1) {
                $where['newhouse.region'] = $region;
            }
            if ($category > -1) {
                $with['structure'] = function($query) {$query->withField('id, category_id, title, flag');};
                $where['structure.category_id'] = $category;
                if ($structure > -1) {
                    $is_layout = in_array('layout', $with);
                    if (!$is_layout) {
                        $with['layout'] = function($query) {$query->withField('id, fan, atype, otype, stype, vtype, floorage, flag');};
                    }
                    if ($structure > -1) {
                        switch ($category) {
                            case 1;
                                $where['layout.fan'] = $structure;
                                break;
                            case 3;
                                $where['layout.atype'] = $structure;
                                break;
                            case 4;
                                $where['layout.otype'] = $structure;
                                break;
                            case 6;
                                $where['layout.stype'] = $structure;
                                break;
                            case 7;
                                $where['layout.vtype'] = $structure;
                                break;
                        }
                    }
                }
            }
            if ($price > -1) {
                $with['price'] = function($query) {$query->withField('id, pay2, flag, updatetime');};
                $_pay = explode('-', $price);
                if ($_pay[1]) {
                    $where['price.pay2'] = [['>', $_pay[0]], ['<=', $_pay[1]], 'and'];
                } else {
                    $where['price.pay2'] = ['>', $_pay[0]];
                }
                $where['price.flag'] = '1';
                $where['price.lx'] = $this->getPrinceLx($category);
            }
            if ($area > -1) {
                $is_layout = in_array('layout', $with);
                if (!$is_layout) {
                    $with['layout'] = function($query) {$query->withField('id, fan, atype, otype, stype, vtype, floorage, flag');};
                }
                $_area = explode('-', $area);
                if ($_area[1]) {
                    $where['layout.floorage'] = [['>', $_area[0]], ['<=', $_area[1]], 'and'];
                } else {
                    $where['layout.floorage'] = ['>', $_area[0]];
                }
            }
            if ($keyword) {
                $where['newhouse.title'] = ['like', '%'.$keyword.'%'];
            }
            $where['newhouse.flag'] = '1';
        } else {
            $order = 'weigh desc';
            $group = 'id';
            if ($region > -1) {
                $where['region'] = $region;
            }
            if ($keyword) {
                $where['title']  = ['like', '%'.$keyword.'%'];
            }
            $where['flag'] = '1';
        }

        $total = $newhouse
            ->with($with)
            ->where($where)
            ->group($group)
            ->count();

        $result = $newhouse
            ->field('id, title, region, covertype, house_image, business_image, houselabel_ids, businesslabel_ids, partnerlabel_id, flag, partner, dynatown, status, weigh')
            ->with($with)
            ->where($where)
            ->order($order)
            ->group($group)
            ->paginate($limit, $total, ['page' => $page]);

        if ($result) {
            $newhouse_dynamic = model('newhouse_dynamic');
            $newhouse_label = model('newhouse_label');
            foreach ($result as $k => $v) {
                $dynamic = $newhouse_dynamic->field('msg')->where('newhouse_id', $v['id'])->order('updatetime desc')->find();
                $result[$k]['dynamic'] = $dynamic?$dynamic['msg']:'不详';
                $houselabel = $newhouse_label->field('name, class')->whereIn('id', $v['houselabel_ids'])->where('status', 1)->limit(2)->select();
                $businesslabel = $newhouse_label->field('name, class')->whereIn('id', $v['businesslabel_ids'])->where('status', 1)->limit(2)->select();
                $partnerlabel = $newhouse_label->field('name, class')->where('id', $v['partnerlabel_id'])->where('status', 1)->find();
                $result[$k]['label'] = $v['covertype']?$businesslabel:$houselabel;
                $result[$k]['partnerlabel'] = $partnerlabel?$partnerlabel:[];
                if ($v['structure_list']) {
                    $newhouse_price = model('newhouse_price');
                    $_structure_list = [];
                    foreach ($v['structure_list'] as $kk => $vv) {
                        $price = $newhouse_price->where('newhouse_id', $vv['newhouse_id'])->where('lx', $this->getPrinceLx($vv['category_id']))->order('updatetime desc')->find();
                        $_structure_list[$kk]['title'] = $vv['title'];
                        $_structure_list[$kk]['class'] = $this->getClass($vv['status']);
                        $_structure_list[$kk]['status_text'] = $this->getStatusText($vv['status']);
                        $_structure_list[$kk]['category'] = $vv['category_id'];
                        $_structure_list[$kk]['category_text'] = $this->getCategoryText($vv['category_id']);
                        $_structure_list[$kk]['is_price'] = $vv['price'];
                        $_structure_list[$kk]['price'] = floatval($price['pay2']?$price['pay2']:($price['pay1']?$price['pay1']:$price['pay3']));
                    }
                    $result[$k]['structureList'] = $_structure_list;
                }
                unset($result[$k]['structure']);
                unset($result[$k]['structure_list']);
                unset($result[$k]['layout']);
                unset($result[$k]['price']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 商铺办公列表
     */
    public function business()
    {
        $limit      = input('limit', 10);
        $page       = input('page', 1);
        $region     = input('region');
        $price      = input('price');
        $category   = input('category');
        $structure  = input('structure');
        $area       = input('area');

        $newhouse   = model('newhouse');
        $with[] = 'structureList';
        $order = 'newhouse.weigh desc';
        $group = 'newhouse.id';

        $with['structure'] = function($query) {$query->withField('id, category_id, title, flag');};
        if ($region > -1) {
            $where['newhouse.region'] = $region;
        }
        if ($category > -1) {
            $where['structure.category_id'] = $category;
            if ($structure > -1) {
                $is_layout = in_array('layout', $with);
                if (!$is_layout) {
                    $with['layout'] = function($query) {$query->withField('id, fan, atype, otype, stype, vtype, floorage, flag');};
                }
                if ($structure > -1) {
                    switch ($category) {
                        case 3;
                            $where['layout.atype'] = $structure;
                            break;
                        case 4;
                            $where['layout.otype'] = $structure;
                            break;
                        case 6;
                            $where['layout.stype'] = $structure;
                            break;
                    }
                }
            }
        } else {
            $where['structure.category_id'] = [['<>', '1'], ['<>', '7'], 'and'];
        }
        if ($price > -1) {
            $with['price'] = function($query) {$query->withField('id, pay2, flag, updatetime');};
            $_pay = explode('-', $price);
            if ($_pay[1]) {
                $where['price.pay2'] = [['>', $_pay[0]], ['<=', $_pay[1]], 'and'];
            } else {
                $where['price.pay2'] = ['>', $_pay[0]];
            }
            $where['price.flag'] = '1';
            $where['price.lx'] = $this->getPrinceLx($category);
        }
        if ($area > -1) {
            $is_layout = in_array('layout', $with);
            if (!$is_layout) {
                $with['layout'] = function($query) {$query->withField('id, fan, atype, otype, stype, vtype, floorage, flag');};
            }
            $_area = explode('-', $area);
            if ($_area[1]) {
                $where['layout.floorage'] = [['>', $_area[0]], ['<=', $_area[1]], 'and'];
            } else {
                $where['layout.floorage'] = ['>', $_area[0]];
            }
        }
        $where['newhouse.flag'] = '1';

        $total = $newhouse
            ->with($with)
            ->where($where)
            ->group($group)
            ->count();

        $result = $newhouse
            ->field('id, title, region, covertype, house_image, business_image, houselabel_ids, businesslabel_ids, partnerlabel_id, flag, partner, dynatown, status, weigh')
            ->with($with)
            ->where($where)
            ->order($order)
            ->group($group)
            ->paginate($limit, $total, ['page' => $page]);

        if ($result) {
            $newhouse_dynamic = model('newhouse_dynamic');
            $newhouse_label = model('newhouse_label');
            foreach ($result as $k => $v) {
                $dynamic = $newhouse_dynamic->field('msg')->where('newhouse_id', $v['id'])->order('updatetime desc')->find();
                $result[$k]['dynamic'] = $dynamic?$dynamic['msg']:'不详';
                $houselabel = $newhouse_label->field('name, class')->whereIn('id', $v['houselabel_ids'])->where('status', 1)->limit(2)->select();
                $businesslabel = $newhouse_label->field('name, class')->whereIn('id', $v['businesslabel_ids'])->where('status', 1)->limit(2)->select();
                $partnerlabel = $newhouse_label->field('name, class')->where('id', $v['partnerlabel_id'])->where('status', 1)->find();
                $result[$k]['label'] = $v['covertype']?$businesslabel:$houselabel;
                $result[$k]['partnerlabel'] = $partnerlabel?$partnerlabel:[];
                if ($v['structure_list']) {
                    $newhouse_price = model('newhouse_price');
                    $_structure_list = [];
                    foreach ($v['structure_list'] as $kk => $vv) {
                        $price = $newhouse_price->where('newhouse_id', $vv['newhouse_id'])->where('lx', $this->getPrinceLx($vv['category_id']))->order('updatetime desc')->find();
                        $_structure_list[$kk]['title'] = $vv['title'];
                        $_structure_list[$kk]['class'] = $this->getClass($vv['status']);
                        $_structure_list[$kk]['status_text'] = $this->getStatusText($vv['status']);
                        $_structure_list[$kk]['category'] = $vv['category_id'];
                        $_structure_list[$kk]['category_text'] = $this->getCategoryText($vv['category_id']);
                        $_structure_list[$kk]['is_price'] = $vv['price'];
                        $_structure_list[$kk]['price'] = floatval($price['pay2']?$price['pay2']:($price['pay1']?$price['pay1']:$price['pay3']));
                    }
                    $result[$k]['structureList'] = $_structure_list;
                }
                unset($result[$k]['structure']);
                unset($result[$k]['structure_list']);
                unset($result[$k]['layout']);
                unset($result[$k]['price']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 详情
     * @internal $id    楼盘ID
     */
    public function view()
    {
        $id = input('id');
        $where['id']    = $id;
        $where['flag']  = '1';
        $newhouse = model('newhouse');
        $newhouse->where('id', $id)->setInc('hits', 1);
        $res = $newhouse->with(['structureList'])->where($where)->find();
        if ($res) {
            $newhouse_developers = model('newhouse_developers');
            $newhouse_property = model('newhouse_property');
            $newhouse_dynamic = model('newhouse_dynamic');
            $newhouse_label = model('newhouse_label');
            $dynamic = $newhouse_dynamic->field('msg')->where('newhouse_id', $res['id'])->order('updatetime desc')->find();
            $houselabel = $newhouse_label->field('name, class')->whereIn('id', $res['houselabel_ids'])->where('status', 1)->limit(5)->select();
            $partnerlabel = $newhouse_label->field('name, class')->where('id', $res['partnerlabel_id'])->where('status', 1)->find();

            $res['developer'] = $newhouse_developers->field('title')->where('id', $res['developer_id'])->find();
            $res['sharedes'] = mb_substr(strip_tags(html_entity_decode($res['content'])), 0, 100); // 分享简介
            $res['dynamic'] = $dynamic?$dynamic['msg']:'不详'; // 动态
            $res['content'] = nl2br(htmlspecialchars_decode($res['content']));
            $res['label'] = $houselabel; // 标签
            $res['partnerlabel'] = $partnerlabel; // 合作标签

            // 楼盘构成
            if ($res['structure_list']) {
                $newhouse_price = model('newhouse_price');
                $_structure_list = [];
                foreach ($res['structure_list'] as $kk => $vv) {
                    $price = $newhouse_price->where('newhouse_id', $vv['newhouse_id'])->where('lx', $this->getPrinceLx($vv['category_id']))->order('updatetime desc')->find();
                    $salelabel = $newhouse_label->field('name, class')->whereIn('id', $vv['salelabel_ids'])->where('status', 1)->limit(5)->select();
                    $ambientlabel = $newhouse_label->field('name')->whereIn('id', $vv['ambientlabel_ids'])->where('status', 1)->select();
                    $ambient = [];
                    if ($ambientlabel) {
                        foreach ($ambientlabel as $item) {
                            $ambient[] = $item['name'];
                        }
                    }
                    $_structure_list[$kk]['title'] = $vv['title'];
                    $_structure_list[$kk]['fan'] = $vv['fan'];
                    $_structure_list[$kk]['building'] = $vv['building'];
                    $_structure_list[$kk]['propertyfee_json'] = $vv['propertyfee_json'];
                    $_structure_list[$kk]['property'] = $newhouse_property->field('title')->where('id', $vv['property_id'])->find();
                    $_structure_list[$kk]['ambientlabel'] = implode(',', $ambient);
                    $_structure_list[$kk]['class'] = $this->getClass($vv['status']);
                    $_structure_list[$kk]['status_text'] = $this->getStatusText($vv['status']);
                    $_structure_list[$kk]['category'] = $vv['category_id'];
                    $_structure_list[$kk]['category_text'] = $this->getCategoryText($vv['category_id']);
                    $_structure_list[$kk]['salelabel'] = $salelabel;
                    $_structure_list[$kk]['is_price'] = $vv['price'];
                    $_structure_list[$kk]['price'] = floatval($price['pay2']?$price['pay2']:($price['pay1']?$price['pay1']:$price['pay3']));
                }
                $res['structureList'] = $_structure_list;
//                unset($res['structure_list']);
            }

            // 置业顾问
            $zygwList = [];
            $dynatown = model('newhouse_dynatown');
            if ($res['dynatown'] == 1) {
                $zygwList = $dynatown
                    ->with(['user','userinfo'])
                    ->where('newhouse_dynatown.newhouse_id', $res['id'])
                    ->where('newhouse_dynatown.status', '1')
                    ->order('newhouse_dynatown.updatetime desc')
                    ->limit(5)
                    ->select();
            } elseif ($res['dynatown'] == 2) {
                $zygwList = $dynatown
                    ->with(['user','userinfo'])
                    ->where('newhouse_dynatown.newhouse_id', '<>', $res['id'])
                    ->where('newhouse.region', $res['region'])
                    ->where('newhouse_dynatown.status', '1')
                    ->orderRaw('rand()')
                    ->limit(5)
                    ->select();
            }
            if ($zygwList) {
                foreach ($zygwList as $row) {
                    $row->visible(['user']);
                    $row->getRelation('user')->visible(['id', 'avatar']);
                    $row->visible(['userinfo']);
                    $row->getRelation('userinfo')->visible(['truename', 'position']);
                }
                $res['zygwList'] = collection($zygwList)->toArray();
            }

            // 楼盘动态
            $news = model("news");
            $lpqb = $news->field('id, image, title, lx, updatetime')->where('title|skey', 'like', '%'.$res['keyword'].'%')->where('lx', '<>', '其它')->where('flag', 1)->order('updatetime', 'desc')->limit(2)->select();
            if ($lpqb) {
                foreach ($lpqb as $k => $v) {
                    $lpqb[$k]['updatetime'] = date('Y-m-d H:i', $v['updatetime']);
                }
            }
            $res['newsList'] = $lpqb;

            // 房价动态
            $price = model("newhouse_price");
            $columnlist = [];
            $seriesList = [];

            // 价格表-住宅
            $_val = [];
            $_tmp = [];
            $subQuery = $price->where('newhouse_id',$res['id'])->where('lx', 0)->order('updatetime desc')->limit(7)->buildSql();
            $zzList = Db::table($subQuery.' zz')->field('pay2, updatetime')->order('updatetime asc')->select();
            if ($zzList) {
                foreach ($zzList as $v) {
                    $_val[] = floatval($v['pay2']);
                    $columnlist[] = $v['updatetime'];
                }
                $_tmp['name'] = '住宅';
                $_tmp['type'] = 'line';
                $_tmp['stack'] = '总量';
                $_tmp['label'] = array(
                    'normal' => array(
                        'show' => true
                    )
                );
                $_tmp['data'] = array_values($_val);
                array_push($seriesList, $_tmp);
            }

            // 价格表-商铺
            $_val = [];
            $_tmp = [];
            $subQuery = $price->where('newhouse_id',$res['id'])->where('lx', 1)->order('updatetime desc')->limit(7)->buildSql();
            $spList = Db::table($subQuery.' sp')->field('pay2, updatetime')->order('updatetime asc')->select();
            if ($spList) {
                foreach ($spList as $v) {
                    $_val[] = floatval($v['pay2']);
                    $columnlist[] = $v['updatetime'];
                }
                $_tmp['name'] = '商铺';
                $_tmp['type'] = 'line';
                $_tmp['stack'] = '总量';
                $_tmp['label'] = array(
                    'normal' => array(
                        'show' => true
                    )
                );
                $_tmp['data'] = array_values($_val);
                array_push($seriesList, $_tmp);
            }

            // 价格表-公寓
            $_val = [];
            $_tmp = [];
            $subQuery = $price->where('newhouse_id',$res['id'])->where('lx', 2)->order('updatetime desc')->limit(7)->buildSql();
            $gyList = Db::table($subQuery.' gy')->field('pay2, updatetime')->order('updatetime asc')->select();
            if ($gyList) {
                foreach ($gyList as $v) {
                    $_val[] = floatval($v['pay2']);
                    $columnlist[] = $v['updatetime'];
                }
                $_tmp['name'] = '公寓';
                $_tmp['type'] = 'line';
                $_tmp['stack'] = '总量';
                $_tmp['label'] = array(
                    'normal' => array(
                        'show' => true
                    )
                );
                $_tmp['data'] = array_values($_val);
                array_push($seriesList, $_tmp);
            }

            // 价格表-别墅
            $_val = [];
            $_tmp = [];
            $subQuery = $price->where('newhouse_id',$res['id'])->where('lx', 3)->order('updatetime desc')->limit(7)->buildSql();
            $bsList = Db::table($subQuery.' bs')->field('pay2, updatetime')->order('updatetime asc')->select();
            if ($bsList) {
                foreach ($bsList as $v) {
                    $_val[] = floatval($v['pay2']);
                    $columnlist[] = $v['updatetime'];
                }
                $_tmp['name'] = '别墅';
                $_tmp['type'] = 'line';
                $_tmp['stack'] = '总量';
                $_tmp['label'] = array(
                    'normal' => array(
                        'show' => true
                    )
                );
                $_tmp['data'] = array_values($_val);
                array_push($seriesList, $_tmp);
            }

            asort($columnlist, SORT_NUMERIC);
            $column = [];
            if ($columnlist) {
                foreach ($columnlist as $val) {
                    $column[] = date('y/m', $val);
                }
            }
            $res['columnList'] = array_values(array_unique($column));
            $res['seriesList'] = $seriesList;

            // 房价动态
            $lpdt = $newhouse_dynamic->where('newhouse_id', $res['id'])->order('updatetime desc')->limit(1, 2)->select();
            if ($lpdt) {
                foreach ($lpdt as $k => $v) {
                    $lpdt[$k]['updatetime'] = date('y/m', $v['updatetime']);
                }
            }
            $res['dynamicList'] = $lpdt;

            // 主推户型
            $layout = model("newhouse_layout");
            $hxt = $layout->field('id, title, fan, tin, wei, floorage, url')->where('newhouse_id', $res['id'])->where('flag', 1)->order('updatetime desc')->limit(6)->select();
            if ($hxt) {
                foreach ($hxt as $k => $v) {
                    $_pic = explode(',', $v['url']);
                    $hxt[$k]['pic'] = $_pic[0];
                    $hxt[$k]['floorage'] = floatval($v['floorage']);
                }
            }
            $res['layoutList'] = $hxt;

            // 楼盘图展
            $realscene = model("newhouse_realscene");
            $realscenelist = model('newhouse_realscenelist');
            $scene = $realscene->field('id, title, image')->where('newhouse_id', $res['id'])->order('id desc')->limit(6)->select();
            if ($scene) {
                foreach ($scene as $k => $v) {
                    $_tmp = [];
                    $realscene = $realscenelist->field('image')->where('realscene_id', $v['id'])->where('flag', '1')->select();
                    if ($realscene) {
                        foreach ($realscene as $item) {
                            $_tmp[] = cdnurl(trim($item['image']));
                        }
                    }
                    $scene[$k]['images'] = $_tmp;
                }
            }
            $res['sceneList'] = $scene;

            // 同区楼盘
            $zblp = $newhouse->field('id, title, region, covertype, house_image, business_image, houselabel_ids, businesslabel_ids, partnerlabel_id')->where('id', '<>', $res['id'])->where('region', $res['region'])->limit(5)->order('updatetime desc')->select();
            if ($zblp) {
                foreach ($zblp as $k => $v) {
                    $dynamic = $newhouse_dynamic->field('msg')->where('newhouse_id', $v['id'])->order('updatetime desc')->find();
                    $hlabel = $newhouse_label->field('name, class')->whereIn('id', $v['houselabel_ids'])->where('status', 1)->limit(2)->select();
                    $blabel = $newhouse_label->field('name, class')->whereIn('id', $v['businesslabel_ids'])->where('status', 1)->limit(2)->select();
                    $plabel = $newhouse_label->field('name, class')->where('id', $v['partnerlabel_id'])->where('status', 1)->find();
                    $zblp[$k]['label'] = $v['covertype']?$blabel:$hlabel;
                    $zblp[$k]['partnerlabel'] = $plabel?$plabel:[];
                    $zblp[$k]['dynamic'] = $dynamic?$dynamic['msg']:'不详';
                }
            }
            $res['zblpList'] = $zblp;

            $this->success('操作成功', $res);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 销售顾问
     * @internal $id    楼盘ID
     */
    public function dynatown()
    {
        $id = input('id');
        $where['newhouse_id'] = $id;
        $where['flag'] = '1';
        $dynatown = model('newhouse_dynatown');
        $result = $dynatown->field('title')->where($where)->select();
        if ($result) {
            $structure = model('newhouse_structure');
            foreach ($result as $k => $v) {
                $label = $structure->field('title')->whereIn('id', $v['structure_ids'])->where('flag', 1)->select();
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }

    }

    /**
     * 房价动态
     * @internal $id    楼盘ID
     */
    public function price()
    {
        $limit  = input('limit', 10);
        $page   = input('page', 1);
        $id     = input('id');

        $price  = model('newhouse_price');
        $where['newhouse_id']   = $id;
        $where['flag']          = 1;
        $total = $price->where($where)->count();
        $result = $price->field('id, pay1, pay2, pay3, msg, updatetime')->where($where)->order('updatetime desc')->paginate($limit, $total, ['page' => $page]);
        if ($result) {
            foreach ($result as $k => $v) {
                $result[$k]['pay1'] = floatval($v['pay1']);
                $result[$k]['pay2'] = floatval($v['pay2']);
                $result[$k]['pay3'] = floatval($v['pay3']);
                $result[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 开盘动态
     * @internal $id    楼盘ID
     */
    public function openlog()
    {
        $limit  = input('limit', 10);
        $page   = input('page', 1);
        $id     = input('id');

        $openlog  = model('newhouse_openlog');
        $where['newhouse_id']   = $id;
        $total = $openlog->where($where)->count();
        $result = $openlog->field('id, tab, openingtime, information, news_id, structure_ids, updatetime')->where($where)->order('updatetime desc')->paginate($limit, $total, ['page' => $page]);
        if ($result) {
            $structure = model('newhouse_structure');
            foreach ($result as $k => $v) {
                $label = $structure->field('title')->whereIn('id', $v['structure_ids'])->where('flag', 1)->select();
                $result[$k]['openingtime'] = substr($v['openingtime'],0 , 10);
                $result[$k]['structure'] = $label;
                $result[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 交房动态
     * @internal $id    楼盘ID
     */
    public function handed()
    {
        $limit  = input('limit', 10);
        $page   = input('page', 1);
        $id     = input('id');

        $handed  = model('newhouse_handed');
        $where['newhouse_id']   = $id;
        $total = $handed->where($where)->count();
        $result = $handed->field('id, deliverdate, information, news_id, structure_ids, updatetime')->where($where)->order('updatetime desc')->paginate($limit, $total, ['page' => $page]);
        if ($result) {
            $structure = model('newhouse_structure');
            foreach ($result as $k => $v) {
                $label = $structure->field('title')->whereIn('id', $v['structure_ids'])->where('flag', 1)->select();
                $result[$k]['structure'] = $label;
                $result[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 预售证动态
     * @internal $id    楼盘ID
     */
    public function salelicense()
    {
        $limit  = input('limit', 10);
        $page   = input('page', 1);
        $id     = input('id');

        $salelicense  = model('newhouse_salelicense');
        $where['newhouse_id']   = $id;
        $total = $salelicense->where($where)->count();
        $result = $salelicense->field('id, serial, serialnote, structure_ids, updatetime')->where($where)->order('updatetime desc')->paginate($limit, $total, ['page' => $page]);
        if ($result) {
            $structure = model('newhouse_structure');
            foreach ($result as $k => $v) {
                $label = $structure->field('title')->whereIn('id', $v['structure_ids'])->where('flag', 1)->select();
                $result[$k]['structure'] = $label;
                $result[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 户型列表
     * @internal $id    楼盘ID
     */
    public function layout()
    {
        $limit      = input('limit', 10);
        $page       = input('page', 1);
        $id         = input('id');
        $category   = input('category');
        $structure  = input('structure');
        $area       = input('area');

        $layout  = model('newhouse_layout');
        $where['newhouse_id'] = $id;
        if ($structure > -1) {
            switch ($category) {
                case 1;
                    $where['fan'] = $structure;
                    break;
                case 3;
                    $where['atype'] = $structure;
                    break;
                case 4;
                    $where['otype'] = $structure;
                    break;
                case 6;
                    $where['stype'] = $structure;
                    break;
                case 7;
                    $where['vtype'] = $structure;
                    break;
            }
        }
        if ($area > -1) {
            $_area = explode('-', $area);
            if ($_area[1]) {
                $where['floorage'] = [['>', $_area[0]], ['<=', $_area[1]], 'and'];
            } else {
                $where['floorage'] = ['>', $_area[0]];
            }
        }
        $where['flag'] = '1';
        $total = $layout->where($where)->count();
        $result = $layout->field('id, title, fan, tin, url, floorage, recommend, updatetime')->where($where)->order('updatetime desc')->paginate($limit, $total, ['page' => $page]);
        if ($result) {
            foreach ($result as $k => $v) {
                $result[$k]['url'] = explode(',', $v['url'])[0];
                $result[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 户型详情
     * @internal $id    楼盘ID
     */
    public function layoutView()
    {
        $id             = input('id');
        $layout         = model('newhouse_layout');
        $label          = model('newhouse_label');
        $realscene      = model('newhouse_realscene');
        $realscenelist  = model('newhouse_realscenelist');
        $structure      = model('newhouse_structure');
        $price          = model('newhouse_price');
        $building       = model('newhouse_building');
        $newhouse       = model('newhouse');
        $where['id']    = $id;
        $where['flag']  = '1';
        $result = $layout->where($where)->find();
        if ($result) {
            $house = $newhouse->field('tel400, dynatown, region')->where('id', $result['newhouse_id'])->find();
            $image = explode(',', $result['url']);
            if ($image) {
                foreach ($image as $k => $v) {
                    $image[$k] = cdnurl($v);
                }
            }
            $result['image'] = $image;
            $result['house'] = $house;
            $result['floorage'] = floatval($result['floorage']);
            $result['innerarea'] = floatval($result['innerarea']);
            $result['usearea'] = floatval($result['usearea']);
            $result['label'] = $label->field('name, class')->whereIn('id', $result['label_ids'])->where('status', 1)->select();
            $result['structure'] = $structure->field('category_id')->with(['newhousecategory'])->where('newhouse_structure.id', $result['structure_id'])->find();
            switch ($result['structure']['category_id']) {
                case '1':
                    $result['category_text'] = $result['htype_text'];
                    break;
                case '3':
                    $result['category_text'] = $result['atype_text'];
                    break;
                case '4':
                    $result['category_text'] = $result['otype_text'];
                    break;
                case '6':
                    $result['category_text'] = $result['stype_text'];
                    break;
                case '7':
                    $result['category_text'] = $result['vtype_text'];
                    break;
            }
            $pay = $price->field('pay2')->where('newhouse_id', $result['newhouse_id'])->where('lx', $this->getPrinceLx($result['structure']['category_id']))->where('flag', '1')->find();
            $result['price'] = floatval($pay['pay2']);
            $result['build'] = $building->field('title, elevator, floor, floorhouse, totalhouse')->whereIn('id', $result['building_ids'])->where('flag', '1')->select();

            // 户型实景
            $realList = [];
            $real = $realscene->where('layout_id', $id)->where('newhouse_id', $result['newhouse_id'])->where('flag', '1')->select();
            if ($real) {
                foreach ($real as $k => $v) {
                    $_tmp = $realscenelist->field('image')->where('realscene_id', $v['id'])->where('flag', '1')->select();
                    if ($_tmp) {
                        foreach ($_tmp as $kk => $vv) {
                            $realList[$kk] = cdnurl(trim($vv['image']));
                        }
                    }
                }
            }
            $result['realscene'] = $realList;

            // 置业顾问
            $zygwList = [];
            $dynatown = model('newhouse_dynatown');
            if ($house['dynatown'] == 1) {
                $zygwList = $dynatown
                    ->with(['user','userinfo'])
                    ->where('newhouse_dynatown.newhouse_id', $result['newhouse_id'])
                    ->where('newhouse_dynatown.status', '1')
                    ->order('newhouse_dynatown.updatetime desc')
                    ->limit(5)
                    ->select();
            } elseif ($house['dynatown'] == 2) {
                $zygwList = $dynatown
                    ->with(['user','userinfo'])
                    ->where('newhouse_dynatown.newhouse_id', '<>', $result['newhouse_id'])
                    ->where('newhouse.region', $house['region'])
                    ->where('newhouse_dynatown.status', '1')
                    ->orderRaw('rand()')
                    ->limit(5)
                    ->select();
            }
            if ($zygwList) {
                foreach ($zygwList as $row) {
                    $row->visible(['user']);
                    $row->getRelation('user')->visible(['id', 'avatar']);
                    $row->visible(['userinfo']);
                    $row->getRelation('userinfo')->visible(['truename', 'position']);
                }
                $result['zygwList'] = collection($zygwList)->toArray();
            }

            // 其它户型
            $hxt = $layout->field('id, structure_id, title, fan, tin, wei, floorage, url')->where('newhouse_id', $result['newhouse_id'])->where('flag', 1)->where('id', '<>', $id)->order('updatetime desc')->limit(5)->select();
            if ($hxt) {
                foreach ($hxt as $k => $v) {
                    $hxt[$k]['url'] = explode(',', $v['url'])[0];
                    $hxt[$k]['floorage'] = floatval($v['floorage']);
                    $hxt[$k]['structure'] = $structure->field('category_id')->with(['newhousecategory'])->where('newhouse_structure.id', $v['structure_id'])->find();
                }
            }
            $result['qthxList'] = $hxt;

            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 楼盘图展
     */
    public function poster()
    {
        $limit      = input('limit', 10);
        $page       = input('page', 1);
        $id         = input('id');
        $type       = input('type');
        $category   = input('category');

        $where['newhouse_id'] = $id;
        switch ($type) {
            case '1':
                $dba  = model('newhouse_realscene');
                if ($category) {
                    $where['category'] = $category;
                }
                $where['flag'] = '1';
                break;
            case '2':
                $dba  = model('newhouse_panorama');
                break;
            case '3':
                $dba  = model('newhouse_video');
                $where['flag'] = '1';
                break;
        }

        $total = $dba->where($where)->count();
        $result = $dba->where($where)->order('createtime desc')->paginate($limit, $total, ['page' => $page]);
        if ($result) {
            if ($type == 1) {
                $realscenelist = model('newhouse_realscenelist');
                foreach ($result as $k => $v) {
                    $_tmp = [];
                    $realscene = $realscenelist->field('image')->where('realscene_id', $v['id'])->where('flag', '1')->select();
                    if ($realscene) {
                        foreach ($realscene as $item) {
                            $_tmp[] = cdnurl(trim($item['image']));
                        }
                    }
                    $result[$k]['images'] = $_tmp;
                }
            }
            $this->success('操作成功', $result);
        } else {
            $this->error('请求错误');
        }
    }

    private function getPrinceLx($val)
    {
        $lx = '0';
        switch ($val) {
            case '1':
                $lx = '0'; // 住宅
                break;
            case '6':
                $lx = '1'; // 商铺
                break;
            case '3':
                $lx = '2'; // 公寓
                break;
            case '7':
                $lx = '3'; // 别墅
                break;
            case '4':
                $lx = '4'; // 写字楼
                break;
        }
        return $lx;
    }

    private function getCategoryText($val)
    {
        $tx = '';
        switch ($val) {
            case '1':
                $tx = '住宅';
                break;
            case '6':
                $tx = '商铺';
                break;
            case '3':
                $tx = '公寓';
                break;
            case '7':
                $tx = '别墅';
                break;
            case '4':
                $tx = '写字楼';
                break;
        }
        return $tx;
    }

    private function getStatusText($val)
    {
        $sx = '';
        switch ($val) {
            case '0':
                $sx = '在售';
                break;
            case '1':
                $sx = '待售';
                break;
            case '2':
                $sx = '售完';
                break;
            case '3':
                $sx = '停售';
                break;
        }
        return $sx;
    }

    private function getClass($val)
    {
        $cs = 'default';
        switch ($val) {
            case '0':
                $cs = 'warning';
                break;
            case '1':
                $cs = 'primary';
                break;
            case '2':
            case '3':
                $cs = 'warning';
                break;
        }
        return $cs;
    }

    /**
     * 移动端新房定投广告 app newhouse adput
     * Api
     *
     * @param int position_id 广告位ID 必选 这里单指移动端广告位ID
     * @param int newhouse_id 楼盘ID 必选
     * @param string area 所属区域名称 必选
     * @param int limit 限制请求一次拿多少数据 可选
     */
    public function appAdputlist()
    {
        // 根据定投 newhouse
        // 根据房产的 所属区域，所属楼盘名，
        // 楼盘直接传id过来
        // 传区域名（不要传区域id）传过来后做区域转 adput区域id转换处理

        // 楼盘ID
        // 必须传值，不然所有的定投楼盘的都会出来
        $newhouse_id = input('newhouse_id', '');
        $area = input('area', '');

        // 区域定投 ， 楼盘定投
        $position_id = input('position_id', 0);
        $limit = input('limit', 0);
        $where['position_id'] = $position_id;
        $where['start_time'] = ['<', time()];
        $where['end_time'] = ['>', time()];
        $where['status'] = '1';
        $areaWhere = array_merge($where, [
            'mode' => ['=', 0],
            'arealist' => ['like', '%' . $this->areaNameToId($area) . '%']
        ]);
        $newhouseWhere = array_merge($where, [
            'mode' => ['=', 1],
            'newhouse_ids' => ['like', '%' . $newhouse_id . '%']
        ]);

        $banner = model('app.adput');
        $banner->where(array('position_id' => $position_id, 'end_time' => array('<', time()), 'status' => 1))->update(['status' => '0']);
        // $list = $app_banner->field('ad_name, ad_file, ad_link')->where($areaWhere)->whereOr($newhouseWhere)->order('weigh desc, updatetime desc')->limit($limit)->select();
        $areaList = $banner->field('id, ad_name, ad_file, ad_link, slogan')->where($areaWhere)->order('weigh desc, updatetime desc')->limit($limit)->select();
        $newhouseList = $banner->field('id, ad_name, ad_file, ad_link, slogan')->where($newhouseWhere)->order('weigh desc, updatetime desc')->limit($limit)->select();
        $list = $this->mergeAdputArray($areaList, $newhouseList);

        if ($list) {
            $res = [];
            foreach ($list as $k => $v) {
                $newspos = explode('?news/id=', $v['ad_link']);
                $newhousepos = explode('?newhouse/id=', $v['ad_link']);
                if (isset($newspos[1]) !== false || isset($newhousepos[1]) !== false) {
                    $res[$k]['nid']     = isset($newspos[1]) !== false ? $newspos[1] : $newhousepos[1];
                    $res[$k]['name']    = $v['ad_name'];
                    $res[$k]['pic']     = explode(',', $v['ad_file']);
                    $res[$k]['url']     = $v['ad_link'];
                    $res[$k]['type']    = isset($newspos[1]) !== false ? 'news' : 'newhouse';
                } else {
                    $urlpos = explode('http', $v['ad_link']);
                    if (isset($urlpos[1]) !== false) {
                        $res[$k]['type']    = 'url';
                    } else {
                        $res[$k]['type']    = 'internal';
                    }
                    $res[$k]['nid']     = 0;
                    // $res[$k]['name']    = $v['ad_name'];
                    $res[$k]['slogan']    = $v['slogan'];
                    $res[$k]['pic']     = explode(',', $v['ad_file']);
                    $res[$k]['url']     = $v['ad_link'];
                }
            }
            // 随机取一值
            $arrKey = array_rand($res, 1);

            $this->success('操作成功', $res[$arrKey]);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 电脑端新房定投广告 newhouse adput
     * Api
     *
     * @param int position_id 广告位ID 必选 这里单指移动端广告位ID
     * @param int newhouse_id 楼盘ID 必选
     * @param string area 所属区域名称 必选
     * @param int limit 限制请求一次拿多少数据 可选
     */
    public function adputlist()
    {
        // 楼盘ID 默认传0.1 是因为这样模糊搜索是绝对没有值出来了
        $newhouse_id = input('newhouse_id', 0.1);
        // 区域名称
        $area = input('area', '');
        $position_id = input('position_id', 0);
        $limit = input('limit', 0);
        $where['position_id'] = $position_id;
        $where['start_time'] = ['<', time()];
        $where['end_time'] = ['>', time()];
        $where['status'] = '1';
        $areaWhere = array_merge($where, [
            'mode' => ['=', 0],
            'arealist' => ['like', '%' . $this->areaNameToId($area) . '%']
        ]);
        $newhouseWhere = array_merge($where, [
            'mode' => ['=', 1],
            'newhouse_ids' => ['like', '%' . $newhouse_id . '%']
        ]);

        $banner = model('ad.adput');
        $banner->where(array('position_id' => $position_id, 'end_time' => array('<', time()), 'status' => 1))->update(['status' => '0']);
        $areaList = $banner->field('id, ad_name, ad_file, ad_link, slogan')->where($areaWhere)->order('weigh desc, updatetime desc')->limit($limit)->select();
        $newhouseList = $banner->field('id, ad_name, ad_file, ad_link, slogan')->where($newhouseWhere)->order('weigh desc, updatetime desc')->limit($limit)->select();
        $list = $this->mergeAdputArray($areaList, $newhouseList);
        if ($list) {
            $res = [];
            foreach ($list as $k => $v) {
                $newspos = explode('?news/id=', $v['ad_link']);
                $newhousepos = explode('?newhouse/id=', $v['ad_link']);
                if (isset($newspos[1]) !== false || isset($newhousepos[1]) !== false) {
                    $res[$k]['nid']     = isset($newspos[1]) !== false ? $newspos[1] : $newhousepos[1];
                    $res[$k]['name']    = $v['ad_name'];
                    $res[$k]['pic']     = explode(',', $v['ad_file']);
                    $res[$k]['url']     = $v['ad_link'];
                    $res[$k]['type']    = isset($newspos[1]) !== false ? 'news' : 'newhouse';
                } else {
                    $urlpos = explode('http', $v['ad_link']);
                    if (isset($urlpos[1]) !== false) {
                        $res[$k]['type']    = 'url';
                    } else {
                        $res[$k]['type']    = 'internal';
                    }
                    $res[$k]['nid']     = 0;
                    // $res[$k]['name']    = $v['ad_name'];
                    $res[$k]['slogan']  = $v['slogan'];
                    $res[$k]['pic']     = explode(',', $v['ad_file']);
                    $res[$k]['url']     = $v['ad_link'];
                }
            }

            $this->success('操作成功', $res);
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 区域名称转为对应 adput定投广告区域id
     * @param  string $name 区域名称
     * @return int    区域id
     */
    protected function areaNameToId($name)
    {
        // adput表定义 0=开发区,1=霞山区,2=赤坎区,3=麻章区,4=坡头区,5=吴川市,6=廉江市,7=雷州市,8=遂溪县,9=徐闻县
        // newhouse表定义 0=开发区,1=霞山,2=赤坎,3=麻章,4=坡头,5=吴川,6=廉江,7=雷州,8=遂溪,9=徐闻
        switch ($name) {
            case '开发区':
                return 0;
                break;
            case '开发':
                return 0;
                break;
            case '霞山区':
                return 1;
                break;
            case '霞山':
                return 1;
                break;
            case '赤坎区':
                return 2;
                break;
            case '赤坎':
                return 2;
                break;
            case '麻章区':
                return 3;
                break;
            case '麻章':
                return 3;
                break;
            case '坡头区':
                return 4;
                break;
            case '坡头':
                return 4;
                break;
            case '吴川市':
                return 5;
                break;
            case '吴川':
                return 5;
                break;
            case '廉江市':
                return 6;
                break;
            case '廉江':
                return 6;
                break;
            case '开发区':
                return 7;
                break;
            case '开发':
                return 7;
                break;
            case '雷州市':
                return 8;
                break;
            case '雷州':
                return 8;
                break;
            case '徐闻县':
                return 9;
                break;
            case '徐闻':
                return 9;
                break;
            default:
                // 一个不存在的区域id
                return 10;
                break;
        }
    }

    /**
     * 合并定投广告数组
     * @param  array $array1
     * @param  array $array2
     * @return array
     */
    protected function mergeAdputArray($array1 = [], $array2 = [])
    {
        $res = [];
        $res2 = [];
        foreach($array1 as $k => $v){
            $res[$v['id']][$k] = $v;
        }

        foreach($array2 as $k => $v){
            $res2[$v['id']][$k] = $v;
        }
        $arr = array_merge($res, $res2);

        $newArr = [];
        foreach ($arr as $k => $v) {
            foreach ($v as $key => $value) {
                $newArr[] = $value;
            }
        }
        return $newArr;
    }

    /**
     * 3D全景列表
     * @return
     */
    public function panorama()
    {
        $page    = input('page', 1);
        $limit   = 10;
        // 新版
        $total = model('newhouse.panorama')->where(['lx'=>1, 'status'=>1])->count();
        $list = model('newhouse.panorama')->where(['lx'=>1, 'status'=>1])->order('id', 'desc')->field('id,title,url1,pic')->paginate($limit, $total, ['page' => $page]);
        // 旧版
        // $total = model('newhouse_panorama')->count();
        // $list = model('newhouse_panorama')->where(['lx'=>1, 'status'=>1])->order('id', 'desc')->field('id,title,url1,pic')->paginate($limit, $total, ['page' => $page]);
        $this->success('操作成功', $list);
    }
}
